package com.demo.passenger.File.web;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/file")
@CrossOrigin
public class FileWeb {

    @CrossOrigin(allowCredentials = "true",maxAge = -1)
    @RequestMapping("/upload")
    public Map upload(@RequestParam(name = "file") MultipartFile file) {
        if (file.isEmpty()) {
            return null;
        }
        Map<String, Object> returnMap = new HashMap<>();
        String filename = file.getOriginalFilename();

        String ext = null;
        if (filename.contains(".")) {
            ext = filename.substring(filename.lastIndexOf("."));
        } else {
            ext = "";
        }
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String fileName = uuid + ext;
        String curDate = DateUtil.format(new Date(), "yyyyMMdd");
        String dirPath = "/passenger-web/file/" + curDate; //DateFormatUtils.format(new Date(), "yyyyMMdd");
        String BASE_PATH = System.getProperty("user.dir");
        String filepath = BASE_PATH.endsWith("/") ? BASE_PATH + dirPath : BASE_PATH + "/" + dirPath;
        File targetFile = new File(filepath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        File toFile = new File(filepath, fileName);
        try {
            file.transferTo(toFile);
            //下载url 等于=日期/id.文件类型
            if (StrUtil.isNotEmpty(ext)) {
                ext = ext.substring(1);
            }
            String downloadUrl = "/api/file/download/" + curDate + "/" + uuid + "/" + ext;
            returnMap.put("uploadSuccess", true);
            returnMap.put("downloadUrl", downloadUrl);
            returnMap.put("uid", uuid);
            returnMap.put("name", fileName);
        } catch (IOException e) {
            e.printStackTrace();
            returnMap.put("uploadSuccess", false);
        }
        return returnMap;
    }

    @RequestMapping("/download/{curDate}/{id}/{type}")
    public String download(HttpServletResponse res, @PathVariable String curDate, @PathVariable String id, @PathVariable String type) {
        String fileName = id + "." + type;
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();

            String BASE_PATH = System.getProperty("user.dir");
            BASE_PATH = BASE_PATH.endsWith("/") ? BASE_PATH : BASE_PATH + "/";
            String filepath = BASE_PATH + "/passenger-web/file/" + curDate + "/" + fileName;
            bis = new BufferedInputStream(new FileInputStream(new File(filepath)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 预览文件，将文件转化成输出流
     *
     * @param response
     * @param curDate
     * @param id
     * @param type
     * @return
     * @throws IOException
     */
    @RequestMapping("/viewPassport/{curDate}/{id}/{type}")
    public String viewPassport(HttpServletResponse response, @PathVariable String curDate, @PathVariable String id, @PathVariable String type) throws IOException {

        String fileName = id + "." + type;
        String BASE_PATH = System.getProperty("user.dir");
        BASE_PATH = BASE_PATH.endsWith("/") ? BASE_PATH : BASE_PATH + "/";
        String filepath = BASE_PATH + "/passenger-web/file/" + curDate + "/" + fileName;

        if (new File(filepath).exists()) {
            FileInputStream inputStream = null;
            OutputStream out = null;
            try {
                inputStream = new FileInputStream(filepath);
                int i = inputStream.available();
                //byte数组用于存放图片字节数据
                byte[] buff = new byte[i];
                inputStream.read(buff);
                //设置发送到客户端的响应内容类型
                response.setContentType("image/*");
                out = response.getOutputStream();
                out.write(buff);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    //关闭输入流
                    inputStream.close();
                }
                if (out != null) {
                    //关闭响应输出流
                    out.close();
                }
            }
        } else {

        }
        return null;
    }

}
